<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_MemberController extends Zend_Controller_Action {

  const SUBMIT_PERSONALIA = 'submit_personalia';
  const SUBMIT_EMAIL = 'submit_email';
  const SUBMIT_PHONE = 'submit_phone';
  const SUBMIT_PERMANENTPASSIVE = 'submit_permanentpassive';
  const SUBMIT_ADDCOURSE = 'submit_addcourse';
  const SUBMIT_ADDCOMPETENCE = 'submit_addcompetence';
  const SUBMIT_COMMENT = 'submit_comment';

    private $_memberService;
    private $_emailService;

  public function init()
  {
    $this->_memberService = $this->_helper->getService('Core_Service_Member');
    $this->_emailService = $this->_helper->getService('Core_Service_Email');
  }

  public function indexAction()
  {
       $filterContent = array(
            'active'    =>  'Aktive',
            'inactive'  =>  'Inaktive',
            'all'       =>  'Alle',
        );
        $filterForm = $this->view->filterForm = $this->view->filterForm($filterContent);
        $filterForm->setAction($this->view->url(array('module' => 'admin', 'controller' => 'member'), null, true));

        $request = $this->getRequest();
        if ($request->isGet() && $this->_getParam('filter', false) && $filterForm->isValid($request->getQuery())) {
            $value = $filterForm->getValue('filter');
            switch ($value) {
                case 'active':
                    $this->view->members = $this->_memberService->fetchAllActive(false);
                    break;
                case 'inactive':
                    $this->view->members = $this->_memberService->fetchAllInActive(false);
                    break;
                case 'all':
                    $this->view->members = $this->_memberService->fetchAllAndJoin(false);
                    break;
            }
        }

        if (!isset($this->view->members)) {
            $this->view->members = $this->_memberService->fetchAllActive(false);
        }
  }

  public function createAction()
  {
        $this->_helper->acl()->isAllowed('service:member', 'create');

        $form = new Admin_Form_Member_Create();

    $request = $this->getRequest();
    if ($request->isPost() && $form->isValid($request->getPost()))
    {
      $result = $this->_memberService->create($form->getValues());
      if ($result) {
                $this->view->flashMessage()->addMessage('Medlemmet ble opprettet', RedCross_View_Helper_FlashMessage::SUCCESS);
                return $this->_helper->redirector('index');
      } else {
        $this->view->unknownError = true;
      }
        }

        $this->view->form = $form;
  }

    public function deleteAction()
    {
        $this->_helper->acl()->isAllowed('service:member', 'delete');

        $memberId = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($memberId)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $memberId = (int) $memberId;

    $member = $this->_memberService->fetch($memberId);
        if (!$member) {
            throw new RedCross_Exception_NotFound();
        }

    $deleteForm = new Admin_Form_Member_Delete();

    $request = $this->getRequest();
    if($request->isPost() && $deleteForm->isValid($request->getPost())) {
      $this->_memberService->delete($memberId);

            $this->view->flashMessage()->addMessage('Markerte medlemmet som inaktivt', RedCross_View_Helper_FlashMessage::SUCCESS);
      $this->_helper->redirector('index');
    }

    $this->view->deleteForm = $deleteForm;
    }

  public function editAction()
    {
        $this->_helper->acl()->isAllowed('service:member', 'edit');

        $memberId = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($memberId)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $memberId = (int)$memberId;
        $this->view->memberId = $memberId;

        $member = $this->_memberService->fetchWithPhoneAndEmail($memberId);
        if(!$member) {
            throw new RedCross_Exception_NotFound();
        }

        $personaliaForm = new Admin_Form_Member_Edit();
        $commentForm = new Admin_Form_Member_Comment();
        $phoneForm = new Admin_Form_Member_Phone();
        $emailForm = new Admin_Form_Member_Email();
        $permanentpassiveForm = new Admin_Form_Member_PermanentPassive();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $values = $request->getPost();
            $flashMessenger = $this->view->flashMessage();

            // Update personalia
            if (isset($values[self::SUBMIT_PERSONALIA]) && $personaliaForm->isValid($values)) {
                $result = $this->_memberService->editPersonalia($memberId, $personaliaForm->getValues());
                $this->view->personaliaMessage = $result ?
                    $flashMessenger->renderMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS) :
                    $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
            } else if (isset($values[self::SUBMIT_COMMENT]) && $commentForm->isValid($values)) {
                $result = $this->_memberService->setComment($memberId, $commentForm->getValues());
                $this->view->personaliaMessage = $result ?
                    $flashMessenger->renderMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS) :
                    $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
            } else if (isset($values[self::SUBMIT_PHONE]) && $phoneForm->isValid($values)) {
                $result = $this->_memberService->addPhone($memberId, $phoneForm->getValues());
                if ($result === Core_Service_Member::PHONE_DUPLICATE) {
                    $this->view->phoneMessage = $flashMessenger->renderMessage('Telefonnummer allerede registrert', RedCross_View_Helper_FlashMessage::ERROR);
                } else if (!$result) {
                    $this->view->phoneMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
                } else {
                    $member = $this->_memberService->fetchWithPhoneAndEmail($memberId);
                    $this->view->phoneMessage = $flashMessenger->renderMessage('Telefonnummer lagt til', RedCross_View_Helper_FlashMessage::SUCCESS);
                    $phoneForm->reset();
                }
            }

            // Update email
            if (isset($values[self::SUBMIT_EMAIL]) && $emailForm->isValid($values)) {
                $result = $this->_memberService->addEmail($memberId, $emailForm->getValues());
                if ($result === Core_Service_Member::EMAIL_DUPLICATE) {
                    $this->view->emailMessage = $flashMessenger->renderMessage('Denne epost-adressen er allerede registrert i systemet', RedCross_View_Helper_FlashMessage::ERROR);
                } else if (!$result) {
                    $this->view->emailMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
                } else {
                    $this->view->emailMessage = $flashMessenger->renderMessage('Epost-adressen er lagt til', RedCross_View_Helper_FlashMessage::SUCCESS);
                    $emailForm->reset();
                }
            }

            // Toggle permanent passive
            if (isset($values[self::SUBMIT_PERMANENTPASSIVE]) && $permanentpassiveForm->isValid($values)) {
                $values = $permanentpassiveForm->getValues();
                $result = $this->_memberService->togglePermanentPassive($memberId, $values);
                if (!$result) {
                    $this->view->permanentPassiveMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
                } else {
                    $this->view->permanentPassiveMessage = $flashMessenger->renderMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS);
                }
            }
        }

        $this->view->isPassive = $this->_memberService->isPermanentPassive($member->id);

        $this->view->member = $member;
        $this->view->personaliaForm = $personaliaForm;
        $this->view->commentForm = $commentForm;
        $this->view->phoneForm = $phoneForm;
        $this->view->emailForm = $emailForm;
        $this->view->permanentPassiveForm = $permanentpassiveForm;

        $personaliaForm->fillForm($member);
        $commentForm->fillForm($member);
        $permanentpassiveForm->fillForm($this->view->isPassive);
  }

  public function removePhoneAction()
  {
        $this->_helper->acl()->isAllowed('service:member', 'edit');

    $this->_helper->viewRenderer->setNoRender(true);
    $phoneId = $this->_getParam('id');

    $validator = new Zend_Validate_Int();
        if (!$validator->isValid($phoneId)) {
            throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt for sletting av telefon: '$phoneId'");
        }
        $phoneId = (int)$phoneId;

        $phoneService = $this->_helper->getService('Core_Service_Phone');
        $phone = $phoneService->fetch($phoneId);
        if (!$phone instanceof Core_Model_Phone) {
          throw new RedCross_Exception_NotFound('Telefonnummer med id ' . $phoneId . ' ikke funnet');
        }
        $memberId = $phone->member_id;
        $success = $phoneService->delete($phone);

        if($success) {
            $this->view->flashMessage()->addMessage('Telefonnummer fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('Minst ett telefonnummer må være registrert', RedCross_View_Helper_FlashMessage::ERROR);
        }
        return $this->_helper->redirector('edit', null, null, array('id' => $memberId));
  }

  public function removeEmailAction()
  {
        $this->_helper->acl()->isAllowed('service:member', 'edit');

    $this->_helper->viewRenderer->setNoRender(true);
    $emailId = $this->_getParam('id');

    $validator = new Zend_Validate_Int();
        if (!$validator->isValid($emailId)) {
            throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt for sletting av epostadresse: '$emailId'");
        }
        $emailId = (int)$emailId;
        $email = $this->_emailService->fetch($emailId);
        if (!is_object($email)) {
          throw new RedCross_Exception_NotFound('Epostadresse med id ' . $emailId . ' ikke funnet');
        }

        $memberId = $email->member_id;
        $success = $this->_emailService->delete($email);

        if($success === Core_Service_Email::EMAIL_DELETE_ERROR_IS_MAIN) {
            $this->view->flashMessage()->addMessage('En hovedepostadresse kan ikke slettes', RedCross_View_Helper_FlashMessage::ERROR);
        } else if($success === Core_Service_Email::EMAIL_DELETE_ERROR_IS_ONLY) {
            $this->view->flashMessage()->addMessage('Minst en epostadresse må være registrert', RedCross_View_Helper_FlashMessage::ERROR);
        } else if($success === true) {
            $this->view->flashMessage()->addMessage('Epostadresse fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('En ukjent feil oppstod under sletting', RedCross_View_Helper_FlashMessage::ERROR);
        }

        return $this->_helper->redirector('edit', null, null, array('id' => $memberId));
  }

  public function setMainEmailAction()
  {
        $this->_helper->acl()->isAllowed('service:member', 'edit');

    $this->_helper->viewRenderer->setNoRender(true);
    $emailId = $this->_getParam('id');
    $validator = new Zend_Validate_Int();
        if (!$validator->isValid($emailId))
        {
            throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt. Skal v&aelig;re int");
        }
        $emailId = (int)$emailId;
        $email = $this->_emailService->fetch($emailId);
        if (!is_object($email))
        {
          throw new RedCross_Exception_NotFound('Epostadresse med angitt id ikke funnet');
        }
        $memberId = $email->member_id;
        $success = $this->_emailService->setAsMain($email);
        return $this->_helper->redirector('edit', null, null, array('id' => $memberId));
  }

    public function coursesAction()
    {
        $this->_helper->acl()->isAllowed('service:member', 'editCourses');

        $member_id = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($member_id)) {
            throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
        }
        $member_id = (int)$member_id;

        $member = $this->_memberService->fetchByIdJoinOnCourse($member_id);
        if (!$member_id) {
          throw new RedCross_Exception_ValidationFailed('Angitt medlem ikke funnet');
        }

        $addCourseForm = new Admin_Form_Member_AddCourse();
        $addCourseForm->fillForm($member_id);
        $this->view->addCourseForm = $addCourseForm;

        $addCompetenceForm = new Admin_Form_Member_AddCompetence();
        $addCompetenceForm->fillForm($member_id);
        $this->view->addCompetenceForm = $addCompetenceForm;

        // TODO: This probably needs to be cleaned up. Probably.

        $request = $this->getRequest();
        $values = $request->getPost();
        if ($request->isPost() && isset($values[self::SUBMIT_ADDCOURSE]) && $addCourseForm->isValid($request->getPost())) {
            $courseAdded = $this->_memberService->addCourse($member_id, $addCourseForm->getValues());
            if (is_object($courseAdded)) {
                $member = $courseAdded;
                $courseAdded = $this->view->flashMessage()->renderMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS);
            } else {
                $courseAdded = $this->view->flashMessage()->renderMessage('Kunne ikke legge til nytt kurs', RedCross_View_Helper_FlashMessage::ERROR);
            }

            $this->view->courseAdded = $courseAdded;
        }

        if ($request->isPost() && isset($values[self::SUBMIT_ADDCOMPETENCE]) && $addCompetenceForm->isValid($request->getPost())) {
            $courseAdded = $this->_memberService->addCourse($member_id, $addCompetenceForm->getValues());
            if (is_object($courseAdded)) {
                $member = $courseAdded;
                $courseAdded = $this->view->flashMessage()->renderMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS);
            } else {
                $courseAdded = $this->view->flashMessage()->renderMessage('Kunne ikke legge til ny kompetanse', RedCross_View_Helper_FlashMessage::ERROR);
            }

            $this->view->courseAdded = $courseAdded;
        }

        $this->view->member = $member;
  }

  public function removeCourseAction()
  {
        $this->_helper->acl()->isAllowed('service:member', 'editCourses');

    $this->_helper->viewRenderer->setNoRender(true);

    $member_id = $this->_getParam('member');
    $course_id = $this->_getParam('course');

    $validator = new Zend_Validate_Int();
        if (!$validator->isValid($member_id) || !$validator->isValid($course_id))
        {
            throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
        }
        $member_id = (int)$member_id;
        $course_id = (int)$course_id;

    $success = $this->_memberService->removeCourse($member_id, $course_id);
        if($success) {
            $this->view->flashMessage()->addMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
        }
    return $this->_helper->redirector('courses', null, null, array('id' => $member_id));
  }
}
